<?php
declare (strict_types = 1);

namespace app\home\controller;

use app\BaseController;
use app\common\model\Region;
use app\common\model\User\User as UserModel;
use app\common\model\Post\Post as PostModel;
use PHPMailer\PHPMailer\PHPMailer;
use think\Request;
use app\common\validate\User\User as UserValiDate;
use think\exception\ValidateException;
use think\facade\View;
use think\facade\Db;

class User extends BaseController
{
    // 设置控制器中间件
    protected $middleware = [
        \app\home\middleware\LoginAuth::class
    ];

    protected function initialize() {
        parent::initialize();
        $this->UserModel = new UserModel();
       
        $LoginUser = !empty(cookie('LoginUser')) ? json_decode(cookie('LoginUser'),true) : [];
        $this->LoginUser = $LoginUser;
    }

    public function index()
    {
        // halt($this->request->LoginUser);
        $User = $this->request->LoginUser;

        $userid = $this->request->param('userid');

        if($userid)
        {
            $User = $this->UserModel->find($userid);
        }

        $PostList = PostModel::where('userid',$User['id'])->order('createtime','desc')->paginate(1);

        // return view();

        return view('',[
            'User' => $User,
            'PostList' => $PostList
        ]);
    }

    public function profile()
    {
        $LoginUser = $this->request->LoginUser;

        if($this->request->isPost())
        {
            $action = $this->request->param('action');

            // if($action == 'profile')

            $user = $this->UserModel->find($LoginUser['id']);

            if(!$user)
            {
                // $param = $this->request->param();
                cookie('LoginUser',null);
                $this->error('非法登录',(String)url('/home/index/login'));
            }

            $avatarold = $user['avatar'];
            $coverold = $user['cover']?substr($user['cover'],1):'';
            if($action == 'profile') {
                $param = $this->request->param();
                $data = [
                    'nickname' => $param['nickname'],
                    'sex' => $param['sex'],
                    'content' => $param['content']
                ];

                if(!empty($param['district']))
                {
                    $parentpath = Region::where('code',$param['district'])->value('parentpath');

                    if(!$parentpath)
                    {
                        $this->error('所选地区不存在，请重新选择');
                    }

                    [$province,$city,$district] = explode(',',$parentpath);

                    if($province)
                    {
                        $data['province'] = $province;
                    }

                    if($province)
                    {
                        $data['city'] = $city;
                    }

                    if($province)
                    {
                        $data['district'] = $district;
                    }
                }

                try {
                    validate(UserValiDate::class)->scene('profile')->check($data);
                } catch (ValidateException $e) {
                    $this->error($e->getError());
                }

                $result = $user->save($data);

                if($result === FALSE)
                {
                    $this->error('更新资料失败');
                }else{
                    
                    $User = $this->UserModel->find($LoginUser['id']);

                    // 封装cookie数组
                    $data = [
                        'id' => $User['id'],
                        'email' => $User['email'],
                        'nickname' => $User['nickname'],
                        'avatar' => $User['avatar'],
                        'sex' => $User['sex'],
                        'province' => $User['province'],
                        'city' => $User['city'],
                        'district' => $User['district'],
                        'content' => $User['content'],
                        'point' => $User['point'],
                        'vip' => $User['vip'],
                        'auth' => $User['auth'],
                        'cover' => $User['cover'],
                        'createtime' => $User['createtime'],
                    ];
                    
                    // 转成json字符串
                    $json = json_encode($data);

                    // cookie 助手函数
                    cookie('LoginUser',$json);

                    $this->success('更新资料成功',(String)url('/home/user/index'));
                }
            }

            if($action == 'avatar')
            {
                $avatar = upload('avatar');

                if($avatar['code'] === 0)
                {
                    $this->error($avatar['msg']);
                }

                $data = [
                    'avatar' => $avatar['data']
                ];

                $result = $user->save($data);

                if($result === FALSE)
                {
                    if($_FILES['avatar']['size'] > 0 && isset($avatar['data']))
                    {
                        @is_file($avatar['data']) && @unlink($avatar['data']);
                    }

                    $this->error('上传失败');
                }else{
                    if($_FILES['avatar']['size'] > 0 && isset($avatar['data']))
                    {
                        @is_file($avatarold) && @unlink($avatarold);
                    }

                    $User = $this->UserModel->find($LoginUser['id']);

                    // 封装cookie数组
                    $data = [
                        'id' => $User['id'],
                        'email' => $User['email'],
                        'nickname' => $User['nickname'],
                        'avatar' => $User['avatar'],
                        'sex' => $User['sex'],
                        'province' => $User['province'],
                        'city' => $User['city'],
                        'district' => $User['district'],
                        'content' => $User['content'],
                        'point' => $User['point'],
                        'vip' => $User['vip'],
                        'auth' => $User['auth'],
                        'cover' => $User['cover'],
                        'createtime' => $User['createtime'],
                    ];
                    
                    // 转成json字符串
                    $json = json_encode($data);

                    // cookie 助手函数
                    cookie('LoginUser',$json);

                    $this->success('上传成功',(String)url('/home/user/index'));
                }
            }

            if($action == 'cover'){
                $cover = upload('cover');
                
                if($cover['code'] === 0)
                {
                 $this->error($cover['msg']);
                }
                
                $data = [
                 'cover' => '/'.$cover['data']
                ];
                
                $result = $user->save($data);
                
                if($result === FALSE)
                {
                 if($_FILES['cover']['size'] > 0 && isset($cover['data']))
                 {
                  @is_file($cover['data']) && @unlink($cover['data']);
                 }
                
                 $this->error('上传失败');
                }else{
                 if($coverold&&$_FILES['cover']['size'] > 0 && isset($cover['data']))
                 {
                  @is_file($coverold) && @unlink($coverold);
                 }
                
                 $User = $this->UserModel->find($LoginUser['id']);
                
                 // 封装cookie数组
                 $data = [
                  'id' => $User['id'],
                  'email' => $User['email'],
                  'nickname' => $User['nickname'],
                  'avatar' => $User['avatar'],
                  'sex' => $User['sex'],
                  'province' => $User['province'],
                  'city' => $User['city'],
                  'district' => $User['district'],
                  'content' => $User['content'],
                  'point' => $User['point'],
                  'vip' => $User['vip'],
                  'auth' => $User['auth'],
                  'cover' => $User['cover'],
                  'createtime' => $User['createtime'],
                 ];
                 
                 // 转成json字符串
                 $json = json_encode($data);
                
                 // cookie 助手函数
                 cookie('LoginUser',$json);
                
                 $this->success('上传成功',(String)url('/home/user/index'));
                }
               }
            
            if($action == 'password') {
                $param = $this->request->param();
                $user = $this->UserModel->find($LoginUser['id']);

                if(!$user) {
                    cookie('LoginUser',null);
                    $this->error('非法登录',(String)url('/home/index/login'));
                }
                $nowpass = $param['nowpass'];
                $pass = $param['pass'];
                $repass = $param['repass'];
                $password = md5($nowpass.$user['salt']);
                
                if($password != $user['password']) {
                    $this->error('原密码错误');
                }
                if($pass != $repass) {
                    $this->error('确认密码与密码不一致');
                }
                $salt = build_ranstr();
                $newpassword = md5($pass.$salt);
                $data = [
                    'password' => $newpassword,
                    'salt' => $salt
                ];

                $result = $user->save($data);

                if($result === FALSE) {
                    $this->error('更新资料失败');
                }else {
                    $User = $this->UserModel->find($LoginUser['id']);

                    // 封装cookie函数
                    $data = [
                        'id' => $User['id'],
                        'email' => $User['email'],
                        'nickname' => $User['nickname'],
                        'avatar' => $User['avatar'],
                        'sex' => $User['sex'],
                        'province' => $User['province'],
                        'city' => $User['city'],
                        'district' => $User['district'],
                        'content' => $User['content'],
                        'point' => $User['point'],
                        'vip' => $User['vip'],
                        'auth' => $User['auth'],
                        'cover' => $User['cover'],
                        'createtime' => $User['createtime'],
                    ];

                    // 转成json字符串
                    $json = json_encode($data);

                    // cookie助手函数
                    cookie('LoginUser',$json);

                    $this->success('修改成功',(String)url('/home/user/index'));
                }
            }
        }

        // return view();

        // 查询所有的数据
        $province = Region::where(['grade' => 1])->select();

        // return view('',['province' => $province]);

        // 查询某个省份市的数据
        if($LoginUser['province']) {
            $city = Region::where('parentid',$LoginUser['province'])->select();
        }else {
            $city = [];
        }

        // 查询某个市 区的数据
        if($LoginUser['city'])
        {
            $district = Region::where('parentid',$LoginUser['city'])->select();
        }else{
            $district = [];
        }
        $action = 'profile';
        return view('',[
            'action' => $action,
            'province' => $province,
            'city' => $city,
            'district' => $district
        ]);
    }

    public function area()
    {
        $code = $this->request->param('code');

        $list = Region::where(['parentid' => $code])->select();

        if(!$list)
        {
            $this->error('所选地区不存在，请重新选择');
        }

        $this->success('查询成功',null,$list);
    }

    public function email()
    {
        // 通过中间件赋值给所有控制器
        $LoginUser = $this->request->LoginUser;

        $salt = $this->UserModel->where(['id' => $LoginUser['id']])->value('salt');

        $email = $this->request->param('email');

        $Email = md5($email.$salt);

        $content = "<a href='http://www.k2217ASK.com/home/index/email?email=$Email'>点击认证</a>";

        // 实例化邮件类
        $mail = new PHPMailer(true);

        // 使用SMTP服务
        $mail->isSMTP(true);

        // 定义SMTP服务地址 qq => 
        $mail->Host = 'smtp.qq.com';

        // 开启认证
        $mail->SMTPAuth = true;

        // 发送内容支持HTML
        $mail->isHTML(true);

        // 邮箱用户名
        $mail->Username = '2190443608@qq.com';

        // 密码 => 在邮箱开启SMTP服务时生成授权码
        $mail->Password = 'aigocecwgrkkeafi';

        // 发件人的名字以及邮箱
        $mail->setFrom('2190443608@qq.com','ASK论坛');

        // 发送的主题
        $mail->Subject = 'ASK论坛邮箱认证激活';

        // 端口 线上服务器 465
        $mail->Port = 25;

        // 设置回复邮箱
        $mail->addReplyTo('2190443608@qq.com','ASK论坛');

        // 收件人
        $mail->addAddress($LoginUser['email'],$LoginUser['nickname']);

        // 设置换行 80字符
        $mail->WordWrap = 80;

        // 添加发送的内容 支持html
        $mail->msgHTML($content);

        // 发送
        $result = $mail->send();

        if($result === FALSE)
        {
            $this->error('发送邮件失败');
        }else{
            $this->success('发送邮件成功');
        }

    }

    public function mypost(){
        $action = 'mypost';
        $state = $this->request->param('state','');
        $accept = $this->request->param('accept','0');
        $where = [];
        $user = $this->LoginUser;
        $where[] = ['userid','=',$user['id']];
        if($state || $state === '0')
        {
         $where[] = ['state','=',$state];
        }
        
        if($accept === '0' || $accept == 1)
        {
         if($accept)
         {
          $where[] = ['accept','exp',Db::raw('IS NOT NULL')];
         }else{
          $where[] = ['accept','exp',Db::raw('IS NULL')];
         }
        }
        $PostList = PostModel::with(['user'])->where($where)->order('createtime','desc')->paginate(['list_rows' => 1,'query' => $this->request->param()]);
        return View::fetch('',[
         'PostList' => $PostList,
         'state' => $state,
         'accept' => $accept,
         'action' => $action
        ]);
       }

}
